package talk.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.KeyEvent;
import android.text.TextUtils;

import talk.Bean.MyUser;
import talk.Bean.Token;
import talk.Data.Constant;
import talk.Net.ChatNet;
import talk.Net.HttpRequest;

import com.talk.debby.talk.R;

import talk.View.MainViewBuild;
import talk.listener.OnBackListener;

import base.BaseActivity;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static io.rong.imkit.utils.SystemUtils.getCurProcessName;

public class MainActivity extends BaseActivity {

    private MainViewBuild mainViewBuild;
    private MainViewBuild.Action action;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mainViewBuild = new MainViewBuild(this);
        doAction();
        mainViewBuild.setAction(action);
    }

    private void doAction() {
        action = new MainViewBuild.Action() {
            @Override
            public void bt_connect(String name, String password) {
                connect(name, password);
            }

            @Override
            public void register() {
                Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    //初始化信息
    private void initData() {
        String userID = getUserID();
        if (!TextUtils.isEmpty(userID)) {
            mainViewBuild.setData(userID);
        }
    }

    //连接
    private void connect(String name, String password) {
        if (TextUtils.isEmpty(name)) {
            showToast("账户不能为空");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            showToast("密码不能为空");
            return;
        }

        login(name, password);
    }

    private void open() {
        Intent intent = new Intent(MainActivity.this, HomeActivity.class);
        startActivity(intent);
    }


    /**
     * 登陆
     *
     * @param name     用户名
     * @param password 用户密码
     */
    private void login(String name, String password) {
        showProgressDialog("登陆中");
        HttpRequest.login(name, password, new Observer<MyUser>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(MyUser myUser) {
                if (myUser != null && myUser.getStatus() == 300) {
                    getToken(myUser);
                } else {
                    if (myUser != null) {
                        showToast(myUser.getMsg());
                    } else {
                        showToast("账号名或密码错误");
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                showToast("账号名或密码错误");
                dismissProgressDialog();
            }

            @Override
            public void onComplete() {
            }
        });

    }


    /**
     * 获取token
     *
     * @param myUser 用户bean
     */
    private void getToken(final MyUser myUser) {
        MyUser.SinfoBean user = myUser.getSinfo();
        HttpRequest.getToken(user.getUid(), user.getUname(), Constant.path, new Observer<Token>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @RequiresApi(api = Build.VERSION_CODES.DONUT)
            @Override
            public void onNext(Token token) {
                if (getApplicationInfo().packageName.
                        equals(getCurProcessName(getApplicationContext()))) {
                    Constant.user = myUser;
                    setUser(myUser);
                    setUserID(myUser.getSinfo().getUid());
                    saveToken(token.getToken());
                    ChatNet.connect(token.getToken(), new OnBackListener() {
                        @Override
                        public void onDo(Boolean success) {
                            dismissProgressDialog();
                            if (success) open();
                        }
                    });
                }
            }

            @Override
            public void onError(Throwable e) {
                showToast("服务器异常");
                dismissProgressDialog();
            }

            @Override
            public void onComplete() {

            }

        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
